package com.yzion.util

import android.content.Intent
import android.net.VpnService
import com.github.shadowsocks.Core
import com.github.shadowsocks.aidl.IShadowsocksService
import com.github.shadowsocks.aidl.ShadowsocksConnection
import com.github.shadowsocks.bg.BaseService
import com.yzion.App
import com.yzion.MainActivity
import com.yzion.baselib.app.BaseApp
import kotlinx.coroutines.Job

object VPNController : ShadowsocksConnection.Callback {
    private val connection = ShadowsocksConnection(false)
    var stateCallback: ((BaseService.State) -> Unit)? = null
    var connectJob: Job? = null
    var cancelConnectCheck = false

    fun register(app: App) {
        Core.init(app, MainActivity::class)
        connection.connect(app.applicationContext, this)
    }

    fun hasVPNPermissionIntent(): Intent? = VpnService.prepare(BaseApp.app.applicationContext)

//    suspend fun prepareServer() = ServerManager.filterFastServer(ServerManager.serverList)

    fun connect() = Core.startService()

    fun stop() = Core.stopService()

    fun tryCancelConnect() {
        if (connectJob?.isActive == true) {
            connectJob?.cancel()
            cancelConnectCheck = true
        }
    }

    override fun stateChanged(state: BaseService.State, profileName: String?, msg: String?) {
        stateCallback?.invoke(state)
    }

    override fun onServiceConnected(service: IShadowsocksService) {}

    override fun onServiceDisconnected() {
        super.onServiceDisconnected()
        connection.disconnect(BaseApp.app.applicationContext)
        connection.connect(BaseApp.app.applicationContext, this)
    }

    override fun onBinderDied() {
        super.onBinderDied()
        stateCallback?.invoke(BaseService.State.Idle)
    }
}